package com.shujia.scala

import scala.io.Source

object Demo29AvgClass {
  def main(args: Array[String]): Unit = {
    //1、统计每个班级总分的平均分
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList

    //解析数据
    val idAndSco: List[(String, Double)] = scores
      .map(line => {
        val split: Array[String] = line.split(",")
        val id: String = split.head
        val sco: Double = split.last.toDouble
        (id, sco)
      })


    //统计学生总分
    val sumScore: Map[String, Double] = idAndSco
      //按照班级分组
      .groupBy(kv => kv._1)
      //计算总分
      .mapValues(value => value.map(_._2).sum)

    sumScore.foreach(println)

    //读取学生表的数据
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList

    //解析数据
    val clazzAndScore: List[(String, Double)] = students
      .map(line => {
        val split: Array[String] = line.split(",")
        val id: String = split.head
        val clazz: String = split.last

        //关联分数表和学生表
        val sumSco: Double = sumScore.getOrElse(id, 0)

        (clazz, sumSco)
      })

    //按照班级分组
    val groupByList: Map[String, List[(String, Double)]] = clazzAndScore
      .groupBy(kv => kv._1)


    //计算平均分
    val clazzAvgScore: Map[String, Double] = groupByList
      .mapValues(value => {
        val scos: List[Double] = value.map(kv => kv._2)
        val avgScore = scos.sum / scos.length
        avgScore
      })

    clazzAvgScore.foreach(println)
  }
}
